package com.hotline.communication.util;

import java.text.MessageFormat;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

public class VxmlUtil {

    private static String VXML_HEADER = "<?xml version=\"1.0\" encoding=\"GB2312\"?>";

    private static String VXML_VERSION = "<vxml version=\"2.0\">";

    private static String VXML_SUFFIX = "</vxml>";

    private static String VXML_VAR = "<var name=\"{0}\" expr=\"{1}\"/>";

    private static String VXML_FORM = "<form><block><log>{0}</log><return namelist=\"{1}\"/></block></form>";

    public static String createVxml(Map<String,String> result){

        if(Objects.isNull(result) || result.isEmpty()){
            return null;
        }

        StringBuffer vxml = new StringBuffer(VXML_HEADER);
        vxml.append(VXML_VERSION);

        StringBuffer nameList = new StringBuffer();

        for(String key : result.keySet()){
            nameList.append(key).append(" ");
            String exp = result.get(key);
            if(StringUtils.isBlank(exp)){
                vxml.append(MessageFormat.format(VXML_VAR,key,"''"));
            }else{
                exp = "'" + exp + "'";
                vxml.append(MessageFormat.format(VXML_VAR,key,exp));
            }

        }
        if(StringUtils.isNotBlank(nameList)){
            vxml.append(MessageFormat.format(VXML_FORM,"log",nameList.substring(0,nameList.length() - 1)));
        }else{
            vxml.append(MessageFormat.format(VXML_FORM,"log",""));
        }

        vxml.append(VXML_SUFFIX);

        return vxml.toString();

    }

    public static String createVxml(){
        String result = "<?xml version=\"1.0\" encoding=\"GB2312\"?><vxml version=\"2.0\"><form><block><log></log></block></form></vxml>";
        return result;
    }

    public static void main(String args[]){

        LinkedHashMap map = new LinkedHashMap();
        map.put("rs","133100000000");
        map.put("rsB","");
        map.put("rsC","");
        map.put("rsD","");
        map.put("rsE","");
        map.put("rsF","");
        map.put("rsG",null);

        System.out.println(VxmlUtil.createVxml(map));

    }
}
